`include "../define.svh"

module norm_add (
    //input clk,
    //input sys_rst_n,
    input signed [7:0] e_in,
    input [27:0] m_sum,
    input [5:0] shift,
    input [1:0] data_type,     
    output reg signed [8:0] e_norm_stage1,
    output [27:0] m_norm_stage1
    //input m_sign // 
);
    //wire signed [25:0] m_add;
    //assign m_add = $signed(m1)+$signed(m2);

    /*wire [25:0] m_unsign;
    assign m_unsign = m_add[25] ? -m_add:m_add;

    assign m_sign = m_add[25];*/


    // 流水线寄存器
    //reg signed [8:0]  e_norm_stage1;
    //wire [27:0] m_norm_stage1;
    assign m_norm_stage1 = m_sum<<shift;

    localparam FP16_OFFSET = 14;
    wire signed [8:0] e_base = $signed({1'b0, e_in}) + FP16_OFFSET;

    // Stage 1: 带溢出处理的组合逻辑
    always @(*) begin
        case (data_type)
            `FP16: begin
                case({m_sum[14],m_sum[13]})
                2'b00:begin
                    e_norm_stage1 = e_base - shift;  // 指数减去移位量
                end
                2'b01:begin
                    e_norm_stage1 = $signed({1'b0,e_in});
                end
                2'b10,2'b11:begin
                    e_norm_stage1 = $signed({1'b0,e_in}) + 9'sd1;      // 指数+1
                end
                default:begin
                    e_norm_stage1 = 9'sd0;
                end
                endcase
            end
            `FP32: begin
                case({m_sum[27],m_sum[26]})
                2'b00:begin
                    e_norm_stage1 = $signed({1'b0,e_in}) - shift + 1;  // 指数减去移位量
                end
                2'b01:begin
                    e_norm_stage1 = $signed({1'b0,e_in});
                end
                2'b10,2'b11:begin
                    e_norm_stage1 = $signed({1'b0,e_in}) + 9'sd1;
                end 
                default:begin
                    e_norm_stage1 = 9'sd0;
                end
                endcase
            end
            default: begin
                e_norm_stage1 = 9'sd0;
            end
        endcase
    end

/*     // Stage 2: 寄存输出
    always @(posedge clk or negedge sys_rst_n) begin
        if (!sys_rst_n) begin
            e_norm <= 9'sd0;
            m_norm <= 28'd0;
        end 
        else begin
            e_norm <= e_norm_stage1;
            m_norm <= m_norm_stage1;
        end
    end */
endmodule